package com.example.main.Conditional.ConditionalOnBean2;

import java.util.List;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

/**
 * ConditionalOnBean2 的实现类
 *
 * @author <a href="920786312@qq.com">周飞</a>
 * @class: OnBean2Condition
 * @date 2021/9/12 14:47
 * @Verson 1.0 -2021/9/12 14:47
 * @see
 */
public class OnBean2Condition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MergedAnnotations annotations = metadata.getAnnotations();
        
        // 获取bean工厂
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        // 没有这个注解
        if (!annotations.isPresent(ConditionalOnBean2.class)) {
            return false;
        }
        
        // 获得注解@ConditionalOnBean2的所有属性
        MultiValueMap<String, Object> allAnnotationAttributes = metadata
                .getAllAnnotationAttributes(ConditionalOnBean2.class.getName());
        // 获取value属性的内容,没有值,就不通过匹配
        List<Object> classList = allAnnotationAttributes.get("value");
        if (classList == null || classList.size() == 0) {
            return false;
        }
        
        Object o = classList.get(0);
        Class cla = null;
        if (o instanceof Class) {
            cla = (Class) o;
        }
        // value 没有值,就不通过匹配
        if (cla == null) {
            return false;
        }
        // 查看当前bean是否存在,存在就返回匹配成功
        String[] beanNamesForType = beanFactory.getBeanNamesForType(cla, true, false);
        if (beanNamesForType != null && beanNamesForType.length > 0) {
            return true;
        }
        return false;
        
    }
    
}